<template>
  <div class="self_adaption">
    <div class="g-container">
      <div class="other">
        <p class="main_text">商品列表</p>
      </div>
      <!-- 搜索 -->
      <div class="g-search" style="padding-top: 0" ref="searchBox">
        <!-- 顶部按钮区域 -->
        <!-- <div class="function_Btn" style="margin-bottom: 10px">
            <el-button class="hollow" @click="exportExcel"
              >导出商品信息</el-button
            >
          </div> -->
        <!-- 时间选择区域 -->
        <div class="search_box1">
          <div class="demo-date-picker">
            <div class="block">
              <span class="demonstration" @change="startTime">商品创建时间：</span>
              <el-date-picker
                v-model="searchValue.startAt"
                type="date"
                placeholder="开始时间"
                @change="startTime"
                :clearable="false"
                :default-time="defaultTime(0, 0, 0)" />

              <span class="demonstration" style="display: inline-block; font-size: 12px; color: #898989; margin: 20px"
                >至</span
              >
              <el-date-picker
                v-model="searchValue.endAt"
                type="date"
                placeholder="结束时间"
                @change="endTime"
                :clearable="false"
                :default-time="defaultTime1(23, 59, 59)" />
            </div>
          </div>
          &emsp;
          <!-- 信息区域 -->
          <div class="all_select">
            <!-- 商品名称 -->
            <div class="input_valye">
              <span class="demonstration">商品名称：</span>
              <input
                type="text"
                class="input"
                placeholder="请输入商品名称"
                v-model="searchValue.name"
                style="width: 180px"
                @keyup.enter="search" />
            </div>
            <!-- 商品条/编码 -->
            <div class="input_valye">
              <span class="demonstration">商品条/编码：</span>
              <input
                type="text"
                class="input"
                placeholder="请输入商品条码"
                v-model="searchValue.productSn"
                style="width: 180px"
                @keyup.enter="search" />
            </div>
            <!-- 商品分组 -->
            <div class="input_valye">
              <span class="demonstration">商品分类：</span>
              <el-tree-select
                v-model="searchValue.type"
                :data="sort"
                :props="{label: 'name', value: 'id'}"
                :render-after-expand="false"
                @change="search">
                <template #default="{data: {name}}">{{ name }}</template>
              </el-tree-select>
            </div>
            <!-- 商品状态 -->
            <!-- <div class="input_valye">
                    <span class="demonstration">商品状态：</span>
                    <el-select
                        v-model="searchValue.status"
                        class="m-2"
                        placeholder="请选择商品状态"
                    >
                        <el-option
                            v-for="item in status_options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </div> -->
          </div>
        </div>
        <!-- 底部按钮区域 -->
        <div class="bottom_btn">
          <el-button class="solid" @click="search">查询</el-button>
          <el-button class="hollow" @click="reset">重置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table">
        <!-- 表格导航栏 -->
        <div class="nav">
          <ul class="nav_ul">
            <li v-for="(item, index) in nav_list" :key="index" :class="item.class" @click="navChange(item)">
              <span class="nav_lis">{{ item.text }}</span>
            </li>
          </ul>
        </div>
        <!-- 表格按钮区域 -->
        <div class="table_function" v-if="roleList.write">
          <el-button class="solid" @click="addGoods">添加商品</el-button>
          <el-button class="solid" @click="publish">上架</el-button>
          <el-button class="hollow" @click="soldOut">下架</el-button>
          <!-- <el-popconfirm confirm-button-text="是" cancel-button-text="否" :icon="InfoFilled" @confirm="DelAll"
            icon-color="#626AEF" title="是否确认删除?">
            <template #reference>
              <el-button type="danger" plain>批量删除</el-button>
            </template>
          </el-popconfirm> -->
        </div>
        <!-- 表格区域 -->
        <el-table
          id="out-table"
          :data="tableData"
          :row-class-name="tableRowClassName"
          @select-all="handleSelectionChange"
          @select="handleSelectionChange"
          :header-cell-style="{'text-align': 'center'}"
          :show-overflow-tooltip="true"
          v-adaptive
          border>
          <el-table-column type="selection" width="40" />
          <el-table-column prop="productSn" label="商品条/编码" width="120" align="center" />
          <el-table-column prop="name" label="商品名" width="100" align="center" />
          <el-table-column prop="pics" label="商品图" width="100" align="center">
            <template #default="item">
              <div v-if="item.row.decoration">
                <div v-if="item.row.decoration.turnImgs[0]">
                  <el-image
                    style="width: 60px; height: 60px"
                    :preview-src-list="item.row.decoration.turnImgs"
                    :src="item.row.decoration.turnImgs[0]"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-teleported="true"
                    :hide-on-click-modal="true"
                    fit="cover" />
                </div>
                <div v-else>
                  <div v-if="item.row.pics.length != 0">
                    <el-image
                      style="width: 60px; height: 60px"
                      :preview-src-list="picsUrl(item.row)"
                      :src="item.row.pics[0].url"
                      :max-scale="7"
                      :min-scale="0.2"
                      :preview-teleported="true"
                      :hide-on-click-modal="true"
                      fit="cover" />
                  </div>
                  <div v-else>
                    <img :src="''" style="width: 100px; height: 100px" />
                  </div>
                </div>
              </div>
              <div v-else>
                <div v-if="item.row.pics.length != 0">
                  <el-image
                    style="width: 60px; height: 60px"
                    :preview-src-list="picsUrl(item.row)"
                    :src="item.row.pics[0].url"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-teleported="true"
                    :hide-on-click-modal="true"
                    fit="cover" />
                </div>
                <div v-else>
                  <img :src="''" style="width: 100px; height: 100px" />
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="salePrice" label="售价" align="center" />
          <el-table-column prop="linePrice" label="划线价" align="center" />
          <el-table-column prop="typeName" label="分类" align="center" />
          <el-table-column prop="createdAt" label="创建时间" width="180" align="center" />
          <el-table-column prop="updatedAt" label="更新时间" width="180" align="center" />
          <el-table-column prop="status" label="状态" align="center">
            <template #default="scope">
              <el-text v-if="scope.row.status == 0" class="mx-1" type="success"> • 未上架</el-text>
              <el-text v-else-if="scope.row.status == 1" class="mx-1" type="primary"> • 已上架</el-text>
              <el-text v-else-if="scope.row.status == 2" class="mx-1" type="warning"> • 已下架</el-text>
              <el-text v-else-if="scope.row.status == 3" class="mx-1" type="warning"> • 售罄</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="库存" width="100" align="center" />
          <el-table-column label="操作" width="200" class="operation">
            <template #default="item" v-if="roleList.write">
              <div class="table_btn">
                <el-button size="small" class="none" @click="bindEditGoods(item.row)">修改</el-button>
                <!-- <el-popconfirm confirm-button-text="是" cancel-button-text="否" :icon="InfoFilled"
                  @confirm="bindDelGoods(item.row.id)" icon-color="#626AEF" title="是否确认删除?">
                  <template #reference>
                    <el-button size="small" class="none_del">删除</el-button>
                  </template>
      </el-popconfirm> -->
                <br />
              </div>
            </template>
          </el-table-column>
        </el-table>
        <smartPager
          v-model:current-page="searchValue.page"
          v-model:page-size="searchValue.rows"
          :total="total"
          @change="pageChange" />
      </div>
      <!-- 添加商品 -->
      <el-form
        ref="ruleFormRef"
        :model="GoodsformDate"
        label-width="120px"
        label-position="right"
        :rules="rules"
        @click="handleClick">
        <div class="publish" v-if="showGoods">
          <div class="publish1">
            <!-- 商品基本信息 -->
            <div class="good_mes"></div>
            <div class="title1" style="position: fixed; width: 70%; z-index: 99">
              <div class="title_mes">
                <el-icon size="20" color="#fff"> <Edit /> </el-icon>&nbsp;商品基础信息
              </div>
              <div class="close" @click="maskBtn1">✖</div>
            </div>
            <div style="height: 80px"></div>

            <div class="content1">
              <p
                style="
                  font-size: 18px;
                  height: 40px;
                  line-height: 40px;
                  border-bottom: 1px solid #dcdfe6;
                  margin-bottom: 20px;
                ">
                商品基础信息
              </p>
              <div style="display: flex; flex-wrap: wrap">
                <el-form-item label="商品OE码:" prop="oeCode">
                  <el-input v-model="GoodsformDate.oeCode" placeholder="请输入OE码" @change="recognitionOecode" /><span
                    style="font-size: 12px; color: red"
                    >* 请尽量填写OE码，以便能被更多用户发现</span
                  >
                  <!-- <el-input
                    v-model="GoodsformDate.oeCode"
                    style="max-width: 600px"
                    placeholder="请输入OE码"
                    class="input-with-select"
                  >
                    <template #append>
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="点击识别OE码"
                        placement="right-end"
                      >
                        <el-button :icon="Search" @click="recognitionOecode" />
                      </el-tooltip>
                    </template> </el-input
                  ><span style="font-size: 12px; color: red"
                    >* 请尽量填写VIN码，以便能被更多用户发现</span
                  > -->
                </el-form-item>
                <el-form-item label="商品VIN码:" prop="VIN码">
                  <el-input
                    v-model="GoodsformDate.vinCode"
                    style="max-width: 600px"
                    placeholder="请输入VIN码"
                    class="input-with-select"
                    @change="VINChange">
                    <template #append>
                      <el-tooltip class="box-item" effect="dark" content="点击识别VIN码" placement="right-end">
                        <span>
                          <el-popover placement="right" :width="520" trigger="click" :visible="VintableBox">
                            <template #reference>
                              <el-button :icon="Search" @click="vinSearch" />
                            </template>
                            <el-table :data="carModelList" @cell-click="vinTableClick">
                              <el-table-column width="100" property="Brand" label="品牌" align="center" />
                              <el-table-column width="100" property="Series" label="车系" align="center" />
                              <el-table-column width="280" property="Model_detail" label="车型" align="center" />
                            </el-table> </el-popover
                        ></span>
                      </el-tooltip>
                    </template> </el-input
                  ><span style="font-size: 12px; color: red">* 请尽量填写VIN码，以便能被更多用户发现</span>
                </el-form-item>
                <el-form-item label="商品名称:" prop="name" style="width: 100%">
                  <el-input v-model="GoodsformDate.name" class="form_input" maxlength="100" show-word-limit />
                  <span id="input_hint"></span>
                </el-form-item>
                <div style="display: flex; flex-wrap: wrap">
                  <el-form-item label="商品品牌:" prop="brand">
                    <div style="position: relative">
                      <div @click.stop="brandSelect">
                        <el-input
                          v-model="GoodsformDate.brand"
                          class="form_input"
                          placeholder="请选择商品品牌"
                          style="width: 220px"
                          @blur="brandClick(GoodsformDate.brand)"
                          @input="searchBrand" />
                      </div>
                      <div
                        v-if="visible"
                        class="menu"
                        style="
                          position: absolute;
                          z-index: 90;
                          background: #fff;
                          box-shadow: #e4e7ed 0px 0px 10px;
                          padding: 5px;
                          top: 32px;
                          border-radius: 5px;
                        ">
                        <div class="city_menu_container" @scroll="onScroll">
                          <div class="area" v-for="(item, index) in brandList" :key="index" style="width: 90%">
                            <div
                              class="itemTit"
                              ref="item.letter"
                              :id="item.letter"
                              style="background: #e0e0e0; padding: 5px">
                              {{ item.letter }}
                            </div>
                            <div
                              class="item action"
                              :class="{
                                active_brand: brandIndex === newIndex && wortIndex === index,
                              }"
                              v-for="(list, newIndex) in item.data"
                              :key="newIndex"
                              @click="chose(list, index, newIndex)">
                              {{ list }}
                            </div>
                          </div>
                        </div>
                        <ul class="city_list_container">
                          <li
                            v-for="(item, index) in wortList"
                            :key="index"
                            @click.stop="jump(index)"
                            style="width: 20px; height: 20px; cursor: pointer">
                            {{ item }}
                          </li>
                        </ul>
                      </div>
                    </div>
                  </el-form-item>
                  <el-form-item label="商品车系:" prop="series">
                    <div style="position: relative">
                      <div @click.stop="SeriesSelect">
                        <el-input
                          v-model="GoodsformDate.series"
                          class="form_input"
                          placeholder="请选择车系"
                          style="width: 220px"
                          @input="searchSerise" />
                      </div>
                      <div
                        v-if="visibleSerise"
                        class="menu"
                        style="
                          position: absolute;
                          z-index: 90;
                          background: #fff;
                          box-shadow: #e4e7ed 0px 0px 10px;
                          padding: 5px;
                          top: 32px;
                          border-radius: 5px;
                          height: 300px;
                        ">
                        <div class="city_menu_container" @scroll="onScroll">
                          <div class="area" v-for="(item, index) in carType" :key="index" style="width: 90%">
                            <div
                              class="itemTit"
                              ref="item.letter"
                              :id="item.letter"
                              style="padding: 5px"
                              @click="carTypeSelect(item)">
                              {{ item.seriesName }}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                  <el-form-item label="商品车型:" prop="modelName">
                    <div style="position: relative">
                      <div @click.stop="modelSelect">
                        <el-input
                          v-model="GoodsformDate.modelName"
                          class="form_input"
                          placeholder="请选择车型"
                          style="width: 220px"
                          @input="searchModel" />
                      </div>
                      <div
                        v-if="visibleModel"
                        class="menu"
                        style="
                          position: absolute;
                          z-index: 90;
                          background: #fff;
                          box-shadow: #e4e7ed 0px 0px 10px;
                          padding: 5px;
                          top: 32px;
                          border-radius: 5px;
                          height: 300px;
                        ">
                        <div class="city_menu_container" @scroll="onScroll">
                          <div class="area" v-for="(item, index) in carSeriesList" :key="index" style="width: 90%">
                            <div
                              class="itemTit"
                              ref="item.letter"
                              :id="item.letter"
                              style="padding: 5px"
                              @click="ModelTypeSelect(item)">
                              {{ item.modelName }}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </div>
                <div style="display: flex; flex-wrap: wrap" v-if="type == 'Add'">
                  <el-form-item label="商品长cm:" prop="length">
                    <el-input v-model="GoodsformDate.length" class="form_input" show-word-limit style="width: 220px" />
                  </el-form-item>
                  <el-form-item label="商品宽cm:" prop="width">
                    <el-input v-model="GoodsformDate.width" class="form_input" show-word-limit style="width: 220px" />
                  </el-form-item>
                  <el-form-item label="商品高cm:" prop="height">
                    <el-input v-model="GoodsformDate.height" class="form_input" show-word-limit style="width: 220px" />
                  </el-form-item>
                  <el-form-item label="商品体积m³:" prop="size">
                    <el-input
                      v-model="GoodsformDate.size"
                      class="form_input"
                      show-word-limit
                      style="width: 220px"
                      :disabled="true" />
                  </el-form-item>
                  <el-form-item label="商品重量kg:" prop="weight">
                    <el-input v-model="GoodsformDate.weight" class="form_input" show-word-limit style="width: 220px" />
                  </el-form-item>
                  <span
                    style="
                      color: red;
                      font-size: 14px;
                      line-height: 32px;
                      margin-left: 30px;
                      cursor: pointer;
                      margin-bottom: 18px;
                    "
                    @click="freight"
                    >点此预估运费</span
                  >
                </div>
                <div style="display: flex; flex-wrap: wrap" v-show="feeShow">
                  <el-form-item label="省内最高">
                    <el-input v-model="provinceHighestFee" :disabled="true">
                      <template #prepend>￥</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="省外最高">
                    <el-input v-model="countryHighestFee" :disabled="true">
                      <template #prepend>￥</template>
                    </el-input>
                  </el-form-item>
                </div>
                <el-form-item label="商品分类:" prop="typeId">
                  <el-tree-select
                    v-model="GoodsformDate.typeId"
                    :data="sort"
                    :props="{label: 'name', value: 'id'}"
                    :render-after-expand="false"
                    style="width: 220px !important">
                    <template #default="{data: {name}}">{{ name }}</template>
                  </el-tree-select>
                </el-form-item>
                <el-form-item label="商品品牌:" prop="other2" v-if="GoodsformDate.typeId == 30">
                  <el-input v-model="GoodsformDate.other2" class="form_input" placeholder="请输入商品品牌" />
                </el-form-item>

                <el-form-item label="商品价格:" prop="salePrice">
                  <el-input v-model="GoodsformDate.salePrice">
                    <template #prepend>￥</template>
                  </el-input> </el-form-item
                >&emsp;
                <el-form-item label="商品划线价:" prop="linePrice">
                  <el-input v-model="GoodsformDate.linePrice">
                    <template #prepend>￥</template>
                  </el-input>
                </el-form-item>
              </div>
              <el-form-item label="商品素材图:" :required="true">
                <div class="photoBox">
                  <el-upload
                    action="#"
                    list-type="picture-card"
                    :auto-upload="false"
                    v-model:file-list="fileList"
                    :on-change="GoodsFiles"
                    ref="uploadImg">
                    <el-icon>
                      <Plus />
                    </el-icon>
                    <template #file="{file}">
                      <div>
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                        <span class="el-upload-list__item-actions">
                          <el-popconfirm
                            confirm-button-text="是"
                            cancel-button-text="否"
                            :icon="InfoFilled"
                            icon-color="#626AEF"
                            title="是否确认删除?"
                            @confirm="handleRemove(file)">
                            <template #reference>
                              <el-icon>
                                <Delete />
                              </el-icon>
                            </template>
                          </el-popconfirm>
                        </span>
                      </div>
                    </template>
                  </el-upload>
                </div>
              </el-form-item>
              <el-form-item label="商品介绍:" prop="description">
                <el-input
                  v-model="GoodsformDate.description"
                  cols="30"
                  rows="4"
                  class="form_input"
                  type="textarea"
                  maxlength="250"
                  show-word-limit></el-input>
              </el-form-item>
              <p
                style="
                  font-size: 18px;
                  height: 40px;
                  line-height: 40px;
                  border-bottom: 1px solid #dcdfe6;
                  margin-bottom: 20px;
                ">
                其他信息
              </p>
              <!-- /*/*/*/*/  商品规格  /*/*/*/*/ -->
              <div style="display: flex; align-items: center; margin-bottom: 20px">
                <span style="font-size: 14px; color: #666; display: inline-block; margin-left: 5px">商品规格:</span>
                <div class="standards" @click="addSku">+添加商品规格</div>
              </div>
              <div class="standars_box" v-for="(item, index) in GoodsformDate.skus" :key="index">
                <el-form-item label="商品规格:" :prop="`skus[${index}].name`" :rules="rules.skus.name">
                  <el-input v-model="item.name" placeholder="请输入商品规格" :maxlength="20" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="规格库存:" :prop="`skus[${index}].inventory`" :rules="rules.skus.inventory">
                  <el-input
                    v-model="item.inventory"
                    placeholder="请输入规格库存"
                    :disabled="GoodsformDate.oeCode !== ''"></el-input>
                </el-form-item>
                <!-- /*/*/*/*/  删除规格  /*/*/*/*/ -->
                <div
                  @click="delSkus(index)"
                  style="
                    width: 20px;
                    height: 20px;
                    border-radius: 50%;
                    text-align: center;
                    line-height: 16px;
                    font-size: 20px;
                    border: 1px solid #9e9e9e;
                    color: #9e9e9e;
                    margin-top: -20px;
                    cursor: pointer;
                  ">
                  -
                </div>
              </div>
              <el-form-item label="商品库存:" prop="inventory" v-if="GoodsformDate.skus.length == 0">
                <el-input
                  v-model="GoodsformDate.inventory"
                  class="form_input"
                  style="width: 200px"
                  :disabled="GoodsformDate.oeCode !== ''" />
                <span id="input_hint"></span>
              </el-form-item>
              <el-form-item label="商品状态:" prop="status">
                <el-select v-model="GoodsformDate.status" class="m-2" placeholder="请选择商品状态">
                  <el-option v-for="item in status_options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="btn_center">
              <el-button class="hollow" @click="maskBtn1">取消</el-button>
              <el-button class="solid" @click="addGoodsBtn(ruleFormRef)" :loading="loading">确定</el-button>
            </div>
          </div>
        </div>
      </el-form>
      <div id="mask1" v-if="showGoods" @click="maskBtn1"></div>
      <canvas ref="canvas" id="canvas" style="display: none"></canvas>
    </div>
  </div>
</template>
<script setup lang="ts">
import {ref, onMounted, reactive, watch, onBeforeUnmount, toRef} from 'vue';
import {ElMessage, ElInput, FormInstance} from 'element-plus';
import moment from 'moment';
import {InfoFilled, Edit, Search, Plus, Delete} from '@element-plus/icons-vue';
import * as imageConversion from 'image-conversion';
import {
  RequestAddGoods,
  RequestDeleteGoods,
  RequestGoodsAmend,
  RequestDeletePhoto,
  RequestGoodSort,
  RequestGoodsSearch,
  RequestDelGoods,
  RequestOnSaleGoods,
  RequestDownGoods,
  RequestCarBrand,
  RequestCarType,
  RequestCarSeries,
  RequestEstimate,
  RequestOeCodeAndEpc,
  RequestRecognizeOeCode,
  RequestRecognizeVinCode,
} from '@/api/path/index.js';
import type {UploadProps} from 'element-plus';
import useAuthorize from '@/hooks/authorize';
/**
 * 返回处理后的图片数组
 */
const picsUrl = (item: any) => {
  let pics = <any>[];
  item.pics.forEach((it: any, index: number) => {
    pics[index] = it.url;
  });
  return pics;
};
let roleList = useAuthorize();
/**
 * 挂载
 */
onMounted(async () => {
  acquireGoods();
  getsort();
  // 获取品牌
  requirBrand('');
  const wid = window.location.search.split('=');
  if (wid[0] == '?push') {
    type.value = 'Add';
    showGoods.value = true;
  }
  handleResize();
  window.addEventListener('resize', handleResize);
});
// 表单规则
const rules = reactive({
  name: [{required: true, message: '请输入商品名', trigger: 'blur'}],
  // unit: [{ required: true, message: '请选择商品单位', trigger: 'change' }],
  typeId: [{required: true, message: '请选择商品分类', trigger: 'change'}],
  skus: {
    name: [{required: true, message: '请输入商品规格', trigger: 'blur'}],
    inventory: [
      {required: true, message: '请输入规格库存', trigger: 'blur'},
      {
        pattern: /^\d+$/,
        message: '请输入正确库存',
        trigger: 'blur',
      },
    ],
  },
  salePrice: [
    {required: true, message: '请输入商品售价', trigger: 'blur'},
    {
      pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
      message: '请输入合法的金额数字，最多两位小数',
      trigger: 'blur',
    },
    {
      validator: (rule, value: any, callback: any) => {
        if (value < 0 || value > 100000) {
          callback(new Error('价格必须在0~100000之间'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  description: [{required: true, message: '请输入商品描述', trigger: 'blur'}],
  linePrice: [
    {
      pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
      message: '请输入合法的金额数字，最多两位小数',
      trigger: 'blur',
    },
  ],
  inventory: [
    {required: true, message: '请输入商品库存', trigger: 'blur'},
    {
      pattern: /^[1-9][0-9]*$/,
      message: '请输入正确库存',
      trigger: 'blur',
    },
  ],
  brand: [{required: true, message: '请选择品牌', trigger: 'change'}],
  series: [{required: true, message: '请选择车系', trigger: 'change'}],
  modelName: [{required: true, message: '请选择车型', trigger: 'change'}],
  status: [{required: true, message: '请选择状态', trigger: 'change'}],
});
/*************************************************************  搜索栏  *************************************************************/

const shopId = Number(localStorage.getItem('ShopId'));
// 搜索参数
const searchValue = ref({
  shopId: shopId,
  name: '',
  productSn: '',
  type: '',
  status: '',
  startAt: '',
  endAt: '',
  page: 1,
  rows: 10,
});
// 状态选择器
const status_options = [
  {
    value: 0,
    label: '未上架',
  },
  {
    value: 1,
    label: '已上架',
  },
  {
    value: 2,
    label: '已下架',
  },
  {
    value: 3,
    label: '售罄',
  },
];
const sort = ref([]); //商品分类
// 获取商品分类
const getsort = async () => {
  const a = await RequestGoodSort();
  sort.value = a.resultObj;
};
/**
 * 时间处理
 */
const defaultTime = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
const defaultTime1 = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
// 开始时间
const startTime = () => {
  searchValue.value.startAt.setHours(0);
  searchValue.value.startAt.setMinutes(0);
  searchValue.value.startAt.setSeconds(0);
  searchValue.value.startAt = moment(searchValue.value.startAt).format('yyyy-MM-DD HH:mm:ss');
  search();
};
// 结束时间
const endTime = () => {
  searchValue.value.endAt.setHours(23);
  searchValue.value.endAt.setMinutes(59);
  searchValue.value.endAt.setSeconds(59);
  searchValue.value.endAt = moment(searchValue.value.endAt).format('yyyy-MM-DD HH:mm:ss');
  search();
};
/**
 * 搜索点击
 */
const search = () => {
  if (moment(searchValue.value.startAt).diff(moment().format('YYYY-MM-DD HH:mm:ss')) >= 0) {
    ElMessage.error('开始时间不能晚于当前日期');
    searchValue.value.startAt = '';
  } else {
    if (searchValue.value.startAt !== '' && searchValue.value.endAt !== '') {
      if (moment(searchValue.value.startAt).diff(moment(searchValue.value.endAt)) <= 0) {
        searchValue.value.page = 1;
        acquireGoods();
      } else {
        ElMessage.error('结束时间不能早于开始时间');
        searchValue.value.endAt = '';
      }
    } else {
      searchValue.value.page = 1;
      acquireGoods();
    }
  }
};
/**
 * 点击重置
 */
const reset = () => {
  searchValue.value = {
    shopId: shopId,
    name: '',
    productSn: '',
    type: '',
    status: '',
    startAt: '',
    endAt: '',
    page: 1,
    rows: 10,
  };
  acquireGoods();
};
/**
 * 获取搜索盒子的高度
 */
const searchBox = ref();
const tablelistHeight = ref();
const handleResize = () => {
  const searchBoxHeight = searchBox.value.clientHeight;
  tablelistHeight.value = 110 + searchBoxHeight + 'px';
};
/*************************************************************  表格相关  *************************************************************/
/**
 * 表格导航列表
 */
const nav_list = ref<any>([
  {
    class: ['navlist', 'nav_li'],
    text: '全部',
    status: '',
  },
  {
    class: ['nav_li'],
    text: '已上架',
    status: 1,
  },
  {
    class: ['nav_li'],
    text: '已售罄',
    status: 3,
  },
  {
    class: ['nav_li'],
    text: '已下架',
    status: 2,
  },
  {
    class: ['nav_li'],
    text: '未上架',
    status: 0,
  },
]);
/**
 * 表格相关数据，事件
 */
const tableData = ref<any>([]); // 表格列表
const total = ref(0); //表格总数
// 获取表格列表
const acquireGoods = async () => {
  const a = await RequestGoodsSearch(searchValue.value);
  if (a.msg == '操作成功！') {
    tableData.value = a.resultObj.products;
    total.value = a.resultObj.totalCount;
  }
};
// 表格颜色区分
const tableRowClassName = ({row, rowIndex}: any) => {
  if (rowIndex % 2 !== 0 || row.selection === true) {
    if (row.selection === true) {
      return 'check_table';
    } else {
      return 'warning-row';
    }
  } else {
    return '';
  }
};
/**
 * 表格导航点击事件
 */
const navChange = (item: any) => {
  nav_list.value.forEach((it: any) => {
    it.class = ['nav_li'];
  });
  searchValue.value.page = 1;
  searchValue.value.status = item.status;
  item.class = ['navlist', 'nav_li'];
  acquireGoods();
};
const producIds = ref<any>([]);
// 表格多选事件
const handleSelectionChange = (selection: any, row: any) => {
  producIds.value = selection;
};

/**
 * 分页
 */
const pageChange = async (val: number) => {
  acquireGoods();
};
// 添加sku
const addSku = () => {
  GoodsformDate.value.skus.push({
    name: '',
    inventory: 0,
  });
};
// 刪除skue
const delSkus = (index: number) => {
  if (GoodsformDate.value.skus[index].id != undefined) {
    skuIds.value.push(GoodsformDate.value.skus[index].id);
  }
  GoodsformDate.value.skus.splice(index, 1);
};

/**
 * 批量删除
 */
const DelAll = () => {
  const a = [];
  for (let i = 0; i < producIds.value.length; i++) {
    a.push(producIds.value[i].id);
  }
  if (a.length !== 0) {
    const formimgs = new FormData();
    formimgs.append('ids', a);
    new Promise((resolve, reject) => {
      RequestDelGoods(formimgs)
        .then((res: any) => {
          resolve(res);
          ElMessage.success('删除成功');
          acquireGoods();
        })
        .catch((err: any) => {
          reject(err);
          ElMessage.error('删除失败');
        });
    });
  } else {
    ElMessage.error('请选择要删除的商品');
  }
};
/**
 * 上架
 */
const isPutaway = ref(false);
const publish = () => {
  isPutaway.value = false;
  const a = [];
  for (let i = 0; i < producIds.value.length; i++) {
    console.log('111111111111111', producIds.value[i]);
    if (producIds.value[i].quantity == 0) {
      ElMessage.error('不能将已售罄的商品上架');
      isPutaway.value = true;
      break;
    } else {
      a.push(producIds.value[i].id);
    }
  }
  if (isPutaway) {
    if (a.length !== 0) {
      const formimgs = new FormData();
      formimgs.append('ids', a);
      new Promise((resolve, reject) => {
        RequestOnSaleGoods(formimgs)
          .then((res: any) => {
            resolve(res);
            ElMessage.success('上架成功');
            acquireGoods();
          })
          .catch((err: any) => {
            reject(err);
            ElMessage.error('上架失败');
          });
      });
    } else {
      ElMessage.error('请选择要上架的商品');
    }
  } else {
    ElMessage.error('不能将已售罄的商品上架');
  }
};
/**
 * 下架
 */
const soldOut = () => {
  const a = [];
  for (let i = 0; i < producIds.value.length; i++) {
    a.push(producIds.value[i].id);
  }
  if (a.length !== 0) {
    const formimgs = new FormData();
    formimgs.append('ids', a);
    new Promise((resolve, reject) => {
      RequestDownGoods(formimgs)
        .then((res: any) => {
          resolve(res);
          ElMessage.success('下架成功');
          acquireGoods();
        })
        .catch((err: any) => {
          reject(err);
          ElMessage.error('下架失败');
        });
    });
  } else {
    ElMessage.error('请选择要下架的商品');
  }
};
// 删除商品
const bindDelGoods = (id: number) => {
  new Promise((resolve, reject) => {
    RequestDeleteGoods(id)
      .then((res: any) => {
        resolve(res);
        acquireGoods();
      })
      .catch((err: any) => {
        reject(err);
      });
  });
};
/*************************************************************  添加编辑商品  *************************************************************/
const showGoods = ref(false); //显示添加商品
const type = ref('Add'); //标识点击的是添加按钮还是编辑按钮
const ruleFormRef = ref<FormInstance>();
const imgs = ref<any>([]); //图片数组
const fileList = ref<UploadUserFile[]>([]); //图片数组
const Editfile = ref<any>([]); //上传的图片数组
// 添加,编辑数据
const GoodsformDate = ref<any>({
  id: '',
  shopId: shopId,
  productSn: '', //商品编号
  name: '', //商品名称
  // unit: '', //单位
  typeId: '', //分类
  salePrice: '', //售价
  linePrice: '', //划线价
  pics: [], //图片数组
  description: '', //商品描述
  skus: [], //规格
  sevenRefund: true, //七天无理由
  openInvoice: true, //是否开发票
  quantity: '', //库存
  productSetting: {
    sevenRefund: true, //七天无理由
    openInvoice: true, //是否开发票
  },
  status: '', //状态
  brand: '其它', //商品品牌
  series: '其它', //车系
  modelName: '其它', //车型名
  other2: '', //车型名
  modelId: '', //车型id
  weight: '', //重量
  oeCode: '', //oe码
  oeMatchBrands: {
    Epc: [],
    Epc_zh: [],
  },
  oeName: '',
  vinCode: '', //Vin码
  vinCodeInfo: {}, //vin码识别
  size: '', //体积
  length: '', //长
  width: '', //宽
  height: '', //高
  // scrapCarId: 0, //溯源
});
const oeCodeBefore = ref(); //编辑前的oe
const vinCodeBefore = ref(); //编辑前的VIN
// 点击编辑
const bindEditGoods = async (item: any) => {
  type.value = 'Edit';
  oeCodeBefore.value = item.oeCode;
  vinCodeBefore.value = item.vinCode;
  isClick.value = false;
  GoodsformDate.value = {
    id: item.id,
    shopId: item.shopId,
    productSn: item.productSn, //商品编号
    name: item.name, //商品名称
    // unit: item.unit, //单位
    typeId: item.typeId, //分类
    skus: item.skus, //规格
    salePrice: item.salePrice, //售价
    status: item.status, //状态
    inventory: item.inventory, //库存
    ship: item.ship, //发货方式
    sevenRefund: true, //七天无理由
    openInvoice: true, //是否开发票
    productSetting: {
      sevenRefund: true, //七天无理由
      openInvoice: true, //是否开发票
    },
    oeCode: item.oeCode, //oe码
    oeMatchBrands: item.oeMatchBrands,
    oeName: item.name,
    vinCode: item.vinCode, //Vin码
    vinCodeInfo: item.vinCodeInfo, //vin码识别
    description: item.description, //商品描述
    // scrapCarId: item.scrapCarId, //溯源
    pics: item.pics, //图片数组
    linePrice: item.linePrice, //划线价
    brand: item.carModel.brandName, //商品品牌
    series: item.carModel.seriesName, //车系
    modelName: item.carModel.modelName, //车型名
    modelId: item.modelId, //车型id
    other2: item.other2, //商品品牌
    weight: item.weight, //重量
    size: item.size, //体积
    length: '', //长
    width: '', //宽
    height: '', //高
  };
  GoodsformDate.value.size = Number(item.size).toFixed(2);
  if (GoodsformDate.value.oeMatchBrands) {
    GoodsformDate.value.oeMatchBrands = JSON.parse(GoodsformDate.value.oeMatchBrands.value);
    if (!GoodsformDate.value.oeMatchBrands.Epc) {
      GoodsformDate.value.oeMatchBrands = {
        Epc: [],
        Epc_zh: [],
      };
    }
  }
  if (GoodsformDate.value.vinCodeInfo) {
    GoodsformDate.value.vinCodeInfo = JSON.parse(GoodsformDate.value.vinCodeInfo.value);
  }
  console.log('编辑', GoodsformDate.value);
  // 获取车系
  const a = await RequestCarType(item.carModel.brandName, '');
  if (a.msg == '操作成功！') {
    carType.value = a.resultObj;
  }
  // 获取车型
  const b = await RequestCarSeries(item.carModel.series, '');
  if (b.msg == '操作成功！') {
    carSeriesList.value = b.resultObj;
    console.log('车型', carSeriesList.value);
  }
  fileList.value = item.pics;
  showGoods.value = true;
};
// 点击添加商品
const addGoods = async (item: any) => {
  type.value = 'Add';
  showGoods.value = true;
  requirBrand('');
};
const watermarkedImage = ref('');
const canvas = ref<any>(null);
const uploadImg = ref();
// 图片上传
const GoodsFiles = (file: any) => {
  console.log(uploadImg.value);

  return new Promise((resolve, reject) => {
    if (
      file.raw.type === 'image/jpeg' ||
      file.raw.type === 'image/jpg' ||
      file.raw.type === 'image/bmp' ||
      file.raw.type === 'image/png' ||
      file.raw.type === 'image/gif' ||
      file.raw.type === 'image/tiff'
    ) {
      console.log('zzzzzzzzzzzzzzzz', file.size);

      if (file.size / 1024 / 1024 > 5) {
        uploadImg.value.handleRemove(file);
        ElMessage.error('该图片大小不能超过5M');
        reject();
      } else {
        imageConversion
          .compressAccurately(file.raw, (file.size / 1024) * 0.6)
          .then((res) => {
            Editfile.value.push(res);
            resolve('验证通过');
          })
          .catch((err) => {
            reject(err);
          });
      }
    } else {
      uploadImg.value.handleRemove(file);
      ElMessage.error('该图片仅支持JPG，JPEG，BMP，PNG，GIF，TIFF');
      reject();
    }
  });
};
/**
 * 添加水印
 */
const watermarked = (file: any) => {
  const file1 = file.raw;
  const ctx = canvas.value.getContext('2d');
  const img = new Image();
  const fileReturn = ref<any>();
  console.log('水印打印图片', file1);

  // 绘制水印
  img.onload = () => {
    canvas.value.width = img.width;
    canvas.value.height = img.height;
    // 绘制原始图片
    ctx.drawImage(img, 0, 0);
    // 绘制水印
    ctx.font = `${img.width * 0.1}px Arial`;
    ctx.fillStyle = 'rgb(189, 189, 189, 0.5)';
    // 获取文字的宽度和高度
    const text = '劣车宝'; //水印默认加店铺的名字
    const textWidth = ctx.measureText(text).width;
    const textHeight = img.width * 0.1; // 根据字体大小设置
    // 计算文字的起始位置
    const x = (img.width - textWidth) / 2; // 水平居中
    const y = (img.height - textHeight) / 2; // 垂直居中
    ctx.fillText(text, x, y);
    // 将canvas转换为DataURL
    const watermarkedDataURL = canvas.value.toDataURL('image/png');
    var arr = watermarkedDataURL.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    var file2 = new File([u8arr], file.raw.name, {type: mime});
    // 更新watermarkedImage
    fileReturn.value = file2;
    watermarkedImage.value = watermarkedDataURL;
  };
  console.log('水印打印图片zzzzzzzzzzzzzzzzzz', URL.createObjectURL(file1));
  img.src = URL.createObjectURL(file1);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(fileReturn.value);
    }, 100);
  });
};
const handleRemove: UploadProps['onRemove'] = async (uploadFile: any, index: any) => {
  if (type.value === 'Add') {
    fileList.value.forEach((item, index) => {
      console.log('111111111', item);
      console.log('111111111', uploadFile);

      if (item.uid == uploadFile.uid) {
        fileList.value.splice(index, 1);
        Editfile.value.splice(index, 1);
      }
      console.log('zzzzzzzzzzzzzzzzzz', fileList.value);
    });
  } else {
    if (uploadFile.id) {
      const a = await RequestDeletePhoto(uploadFile.id);
      if (a.msg == '操作成功！') {
        ElMessage.success('操作成功');
        fileList.value.forEach((item, index) => {
          if (item.uid == uploadFile.uid) {
            fileList.value.splice(index, 1);
            Editfile.value.splice(index, 1);
          }
        });
      } else {
        ElMessage.error('操作失败');
      }
    } else {
      fileList.value.forEach((item, index) => {
        if (item.uid == uploadFile.uid) {
          fileList.value.splice(index, 1);
          Editfile.value.splice(index, 1);
        }
      });
      ElMessage.success('操作成功');
    }
  }
};
/**
 * 监听商品长宽高的变化
 */
watch(
  () => [GoodsformDate.value.length, GoodsformDate.value.width, GoodsformDate.value.height],
  (newVal, oldVal) => {
    if (type.value == 'Add') {
      console.log('监听变化', newVal, oldVal); // [11, 22], [1, 2]
      GoodsformDate.value.size = ((newVal[0] * newVal[1] * newVal[2]) / 1000000).toFixed(2);
    }
  },
);
/**
 * 识别oe码
 */
const brandName = ref([]);
const VintableBox = ref(false); //控制消息弹出框的显示
const recognitionOecode = async () => {
  if (GoodsformDate.value.oeCode) {
    const a = await RequestRecognizeOeCode(GoodsformDate.value.oeCode);
    if (a.msg == '操作成功！') {
      if (a.resultObj.msg == '您的账号已过期，请联系客服续期！') {
        ElMessage.error('您的账号已过期，请联系客服续期');
      } else {
        brandName.value = [];
        for (let i = 0; i < a.resultObj.length; i++) {
          brandName.value = brandName.value.concat(a.resultObj[i].Epc_zh.split(','));
          GoodsformDate.value.oeMatchBrands.Epc.push(a.resultObj[i].Epc);
        }
        GoodsformDate.value.oeMatchBrands.Epc_zh = Array.from(new Set(brandName.value));
        GoodsformDate.value.oeMatchBrands.Epc = Array.from(new Set(GoodsformDate.value.oeMatchBrands.Epc));
        const b = await RequestOeCodeAndEpc(GoodsformDate.value.oeCode, a.resultObj[0].Epc);
        if (b.msg == '操作成功！') {
          GoodsformDate.value.oeName = b.resultObj.searchlist[0].name_zh;
          GoodsformDate.value.name = b.resultObj.searchlist[0].name_zh;
          if (GoodsformDate.value.skus.length == 0) {
            GoodsformDate.value.inventory = 1;
          } else {
            GoodsformDate.value.skus = GoodsformDate.value.skus.splice(0, 1);
            GoodsformDate.value.skus[0].inventory = 1;
          }

          ElMessage.success('识别成功');
        } else {
          ElMessage.error('识别失败！');
          GoodsformDate.value.oeCode = '';
          GoodsformDate.value.oeMatchBrands = {
            Epc: [],
            Epc_zh: [],
          };
        }
      }
    } else {
      GoodsformDate.value.oeCode = '';
      ElMessage.error('识别失败！');
      GoodsformDate.value.oeMatchBrands = {
        Epc: [],
        Epc_zh: [],
      };
    }
  }
};
/**
 * 识别vin码
 */
const carModelList = ref([]);
const isClick = ref(false); //是否点击
const vinSearch = async () => {
  const a = await RequestRecognizeVinCode(GoodsformDate.value.vinCode);
  if (a.msg == '操作成功！') {
    carModelList.value = a.resultObj;
    VintableBox.value = true;
    console.log('识别', carModelList.value);
    isClick.value = true;
  } else {
    if (a.msg) {
      ElMessage.error(a.msg);
    } else {
      ElMessage.error(a.message);
    }
    isClick.value = false;
  }
};
/**
 * 修改VIN码
 */
const VINChange = () => {
  GoodsformDate.value.vinCodeInfo = {};
  console.log('zzzzz', GoodsformDate.value);
};
/**
 * 点击选择vin识别的品牌车型车系
 */
const vinTableClick = (row: any) => {
  console.log(row);
  VintableBox.value = false;
  GoodsformDate.value.vinCodeInfo = row;
  GoodsformDate.value.brand = row.Brand; //商品品牌
  GoodsformDate.value.series = row.Series; //车系
  GoodsformDate.value.modelName = row.Model; //车型名
};
let timer = ref(); //设置记录时间，用于防抖
const loading = ref(false);
/**
 * 添加,编辑商品确认按钮
 */
const vinRecognition = ref(false);
const addGoodsBtn = async (formEl: any) => {
  vinRecognition.value = false;
  if (!formEl) return;
  await formEl.validate(async (valid: any, fields: any) => {
    if (valid) {
      clearTimeout(timer.value);
      timer.value = setTimeout(async () => {
        loading.value = true;
        // 判断是否所有的sku都有库存
        const allNum = GoodsformDate.value.skus.every((sku: any) => sku.inventory != 0);
        /**********************************  添加  **********************************/
        if (type.value === 'Add') {
          // 识别oe码
          // const mes = await recognitionOecode();
          // if (mes == '成功') {
          // 识别VIN码
          if (!GoodsformDate.value.vinCodeInfo && GoodsformDate.value.vinCode) {
            ElMessage.error('请先点击VIN后的识别框，并选择当前车系');
            loading.value = false;
          } else {
            const photoWatermarked = new FormData();
            //判断是否上传图片
            if (Editfile.value.length == 0) {
              ElMessage.error('请选择图片！');
              loading.value = false;
            } else {
              // 判断没有库存的商品不能上架
              if (!allNum && GoodsformDate.value.status == 1) {
                ElMessage.error('不能将没有库存的商品上架');
                loading.value = false;
              } else {
                for (let i = 0; i < Editfile.value.length; i++) {
                  //判断是否添加需要水印
                  // const a = await watermarked(Editfile.value[i]);
                  photoWatermarked.append('imgs', Editfile.value[i]);
                }
                // 给参数添加请求头
                const blob = new Blob([JSON.stringify(GoodsformDate.value)], {
                  type: 'application/json;charset=utf-8',
                });
                photoWatermarked.append('product', blob);
                const a = await RequestAddGoods(photoWatermarked);
                if (a.msg == '操作成功！') {
                  ElMessage.success('添加成功');
                  loading.value = false;
                  acquireGoods();
                  fileList.value = [];
                  maskBtn1();
                  // 发布成功后清空所有的东西
                  showGoods.value = false;
                  imgs.value = []; //图片数组
                  Editfile.value = [];
                } else {
                  ElMessage.error('添加失败');
                  fileList.value = [];
                  loading.value = false;
                }
                console.log('添加商品信息', GoodsformDate.value);
              }
            }
          }
          // } else {
          //   ElMessage.error('因识别失败，将清空oe码');
          //   GoodsformDate.value.oeCode = '';
          //   loading.value = false;
          // }
        } else {
          /**********************************  编辑  **********************************/
          if (!allNum && GoodsformDate.value.status == 1) {
            ElMessage.error('不能将没有库存的商品上架');
            loading.value = false;
          } else {
            // const mes = await recognitionOecode();
            // if (mes == '成功') {
            // 是否填写vin码
            if (GoodsformDate.value.vinCode) {
              if (!GoodsformDate.value.vinCodeInfo) {
                ElMessage.error('请先点击VIN后的识别框，并选择当前车系');
                loading.value = false;
              } else {
                if (vinCodeBefore.value != GoodsformDate.value.vinCode && !isClick.value) {
                  ElMessage.error('请先点击VIN后的识别框，并选择当前车系');
                  loading.value = false;
                } else {
                  vinRecognition.value = true;
                }
              }
            } else {
              vinRecognition.value = true;
            }
            if (vinRecognition.value) {
              const formimgs = new FormData();
              for (let i = 0; i < Editfile.value.length; i++) {
                // const a = await watermarked(Editfile.value[i]);
                formimgs.append('imgs', Editfile.value[i]);
              }
              delete GoodsformDate.value.pics;
              const blob = new Blob([JSON.stringify(GoodsformDate.value)], {
                type: 'application/json;charset=utf-8',
              });
              console.log('表单信息', GoodsformDate.value);

              const blob1 = new Blob([JSON.stringify(skuIds.value)], {
                type: 'application/json;charset=utf-8',
              });
              formimgs.append('product', blob);
              formimgs.append('skuIds', blob1);
              const a = await RequestGoodsAmend(formimgs);
              if (a.msg == '操作成功！') {
                acquireGoods();
                fileList.value = [];
                loading.value = false;
                ElMessage.success('操作成功！');
                maskBtn1();
                // 发布成功后清空所有的东西
                showGoods.value = false;
                imgs.value = []; //图片数组
                Editfile.value = [];
              } else {
                fileList.value = [];
                loading.value = false;
                ElMessage.error('操作失败！请重试');
              }
            }
            // } else {
            //   ElMessage.error('因识别失败，将清空oe码');
            //   GoodsformDate.value.oeCode = '';
            //   GoodsformDate.value.oeMatchBrands = {
            //     Epc: [],
            //     Epc_zh: [],
            //   };
            //   loading.value = false;
            // }
          }
        }
      }, 500);
    } else {
      ElMessage.error('请先完善商品的相关信息！');
    }
  });
};
const feeShow = ref(false);
const provinceHighestFee = ref(0);
const countryHighestFee = ref(0);
/**
 * 预估运费
 */
const freight = async () => {
  if (GoodsformDate.value.weight && GoodsformDate.value.size) {
    const a = await RequestEstimate({
      totalWeight: GoodsformDate.value.weight,
      totalVolume: GoodsformDate.value.size,
    });
    if (a.msg == '操作成功！') {
      feeShow.value = true;
      provinceHighestFee.value = a.resultObj.provinceHighestFee;
      countryHighestFee.value = a.resultObj.countryHighestFee;
    }
  } else {
    ElMessage.error('请输入商品体积和重量！');
  }
};
/*************************************************************  品牌，车型，车系  *************************************************************/
const brandList = ref<any>([]); //品牌数组
// 手写字母数组
const wortList = ref([
  '#',
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z',
]);
/**
 * 根据关键字获取品牌
 */
const requirBrand = async (e: String) => {
  const a = await RequestCarBrand(e);
  brandList.value = JSON.parse(
    JSON.stringify(a.resultObj).replaceAll('firstLetter', 'letter').replaceAll('brands', 'data'),
  );
};
const carType = ref<any>([]); //车型
const carSeriesList = ref<any>([]); //车系
const skuIds = ref<any>([]);
const activeStep = ref();
const brandIndex = ref();
const wortIndex = ref();
const inpVal = ref();
const visible = ref(false);
const visibleSerise = ref(false);
const visibleModel = ref(false);
const handleClick = () => {
  visible.value = false;
  visibleSerise.value = false;
  visibleModel.value = false;
  VintableBox.value = false;
};
/**
 * 点击品牌输入框
 */
const brandSelect = () => {
  visible.value = true;
  visibleSerise.value = false;
  visibleModel.value = false;
};
/**
 * 点击车系输入框
 */
const SeriesSelect = () => {
  visibleSerise.value = true;
  visible.value = false;
  visibleModel.value = false;
};
/**
 * 点击车型输入框
 */
const modelSelect = () => {
  visibleModel.value = true;
  visible.value = false;
  visibleSerise.value = false;
};
const onScroll = (e: any) => {
  let scrollItems = document.querySelectorAll('.itemTit');
  for (let i = scrollItems.length - 1; i >= 0; i--) {
    // 判断滚动条滚动距离是否大于当前滚动项可滚动距离
    let judge = e.target.scrollTop >= scrollItems[i].offsetTop - scrollItems[0].offsetTop;
    if (judge) {
      activeStep.value = i;
      break;
    }
  }
};
const jump = (index: number) => {
  let target = document.querySelector('.city_menu_container');
  let scrollItems = document.querySelectorAll('.area');
  // 判断滚动条是否滚动到底部
  if (target!.scrollHeight <= target!.scrollTop + target!.clientHeight) {
    activeStep.value = index;
  }
  let roll = scrollItems[index].offsetTop - scrollItems[0].offsetTop; // 锚点元素距离其滚动窗口顶部的距离(待滚动的距离)
  let distance = document.querySelector('.city_menu_container')!.scrollTop; // 滚动条距离滚动区域顶部的距离
  // 滚动条距离滚动区域顶部的距离(滚动区域为窗口)
  // 滚动动画实现, 使用setTimeout的递归实现平滑滚动，将距离细分为10小段，10ms滚动一次
  // 计算每一小段的距离
  let step = roll / 10;
  if (roll > distance) {
    rollDown(target);
  } else {
    let newTotal = distance - roll;
    step = newTotal / 10;
    rollUp(target);
  }
  // node为滚动区域节点
  function rollDown(node: any) {
    if (distance < roll) {
      distance += step;
      node.scrollTop = distance;
      setTimeout(rollDown.bind(this, node), 10);
    } else {
      node.scrollTop = roll;
    }
  }
  // node为滚动区域节点
  function rollUp(node: any) {
    if (distance > roll) {
      distance -= step;
      node.scrollTop = distance;
      setTimeout(rollUp.bind(this, node), 10);
    } else {
      node.scrollTop = roll;
    }
  }
};
// 点击品牌列表
const chose = (e: any, index: number, newIndex: number) => {
  brandIndex.value = newIndex;
  wortIndex.value = index;
  // this.$emit('closeList', e)
  GoodsformDate.value.brand = e;
  GoodsformDate.value.series = '';
  GoodsformDate.value.modelName = '';
  GoodsformDate.value.modelId = null;
  closeList(e);
  brandClick(e);
};
const closeList = (val: any) => {
  inpVal.value = val;
  visible.value = false;
};
/**
 * 选择品牌，获取车系
 */
const brandClick = async (e: any) => {
  const a = await RequestCarType(e, '');
  console.log(GoodsformDate.value);

  if (a.msg == '操作成功！') {
    carType.value = a.resultObj;
  }
};
/**
 * 根据关键字匹配品牌
 */
let time = ref();
const searchBrand = () => {
  if (time != null) {
    clearTimeout(time.value);
  }
  time.value = setTimeout(() => {
    requirBrand(GoodsformDate.value.brand);
  }, 500);
};
const searchSerise = () => {
  if (time != null) {
    clearTimeout(time.value);
  }
  time.value = setTimeout(async () => {
    const a = await RequestCarType(GoodsformDate.value.brand, GoodsformDate.value.series);
    console.log(GoodsformDate.value);

    if (a.msg == '操作成功！') {
      carType.value = a.resultObj;
    }
  }, 500);
};
const searchModel = () => {
  if (time != null) {
    clearTimeout(time.value);
  }
  time.value = setTimeout(async () => {
    const a = await RequestCarSeries(GoodsformDate.value.series, GoodsformDate.value.modelName);
    console.log(GoodsformDate.value);

    if (a.msg == '操作成功！') {
      carSeriesList.value = a.resultObj;
    }
  }, 500);
};

// 选择车系
const carTypeSelect = async (item: any) => {
  GoodsformDate.value.series = item.seriesName;
  GoodsformDate.value.modelName = '';
  GoodsformDate.value.modelId = null;
  const a = await RequestCarSeries(item.seriesName, '');
  if (a.msg == '操作成功！') {
    carSeriesList.value = a.resultObj;
  }
};
const ModelTypeSelect = (item: any) => {
  GoodsformDate.value.modelName = item.modelName;
};
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});
/**
 * 遮罩层数据，事件
 */
const maskBtn1 = () => {
  showGoods.value = false;
  feeShow.value = false;
  skuIds.value = [];
  oeCodeBefore.value = '';
  VintableBox.value = false;

  loading.value = false;
  acquireGoods();
  handleClick();
  GoodsformDate.value = {
    id: '',
    shopId: shopId,
    productSn: '', //商品编号
    name: '', //商品名称
    // unit: '', //单位
    typeId: '', //分类
    salePrice: '', //售价
    linePrice: '', //划线价
    pics: [], //图片数组
    description: '', //商品描述
    skus: [], //规格
    sevenRefund: true, //七天无理由
    openInvoice: true, //是否开发票
    quantity: '', //库存
    productSetting: {
      sevenRefund: true, //七天无理由
      openInvoice: true, //是否开发票
    },
    status: '', //状态
    brand: '其它', //商品品牌
    series: '其它', //车系
    modelName: '其它', //车型名
    other2: '', //车型名
    modelId: '', //车型id
    weight: '', //重量
    oeCode: '', //oe码
    oeMatchBrands: {
      Epc: [],
      Epc_zh: [],
    },
    oeName: '',
    vinCode: '', //Vin码
    vinCodeInfo: {}, //vin码识别
    size: '', //体积
    length: '', //长
    width: '', //宽
    height: '', //高
    // scrapCarId: 0, //溯源
  };

  fileList.value = [];
  imgs.value = []; //图片数组
};
</script>
<style lang="scss" scoped>
@import '@/assets/css/plateform/Article/Content.css';
@import '@/assets/css/plateform/Shop/GoodsManage.css';
.g-container {
  align-content: flex-start;
  flex-direction: column;
}

.table {
  height: calc(100% - v-bind(tablelistHeight)) !important;
}

::v-deep .el-table--fit {
  height: calc(100% - 120px) !important;
}

.menu {
  width: 220px;
  height: 550px;
  display: flex;
  flex-wrap: wrap;
  position: relative;

  .city_menu_container {
    width: 100%;
    height: 100%;
    overflow-y: scroll;

    .item {
      width: 80%;
      word-break: break-all;
      margin: 20px 0;
    }
  }

  .city_list_container {
    width: 20%;
    position: absolute;
    right: 10px;
  }
}

.city_menu_container::-webkit-scrollbar {
  display: none !important;
}

.table :deep(.el-table__cell) {
  text-align: center;
}

.el-select {
  width: 224px;
}

.nav_ul {
  width: 100%;

  .nav_li {
    width: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .nav_lis {
    position: relative;
    cursor: pointer;

    .number {
      padding: 0 5px;
      display: block;
      line-height: 16px;
      height: 16px;
      color: #fff;
      font-size: 12px;
      background: #409eff;
      border-radius: 8px;
      position: absolute;
      top: 2px;
      right: -12px;
    }
  }

  .navlist {
    .number {
      background: #409eff;
      color: #fff;
    }
  }
}

.standards {
  width: 100px;
  height: 30px;
  border: 1px solid #116cf8;
  color: #116cf8;
  text-align: center;
  font-size: 12px;
  line-height: 30px;
  border-radius: 5px;
  margin-left: 35px;
  cursor: pointer;
}

.standars_box {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between;
  margin-bottom: 20px;

  .box_left {
    width: 48%;
    display: flex;
    align-items: center;
  }

  .box_right {
    width: 48%;
    display: flex;
    align-items: center;
  }

  .goods_skus {
    display: inline-block;
    width: 150px;
    font-size: 14px;
    color: #606266;
  }
}

::v-deep .el-select {
  position: relative;
  border-color: red;
}

.popover {
  position: absolute;
  top: 0;
}

::v-deep .el-dialog__header {
  height: 60px !important;
}

::deep(.el-dialog__header) {
  height: 60px !important;
}

::v-deep .el-table {
  flex: 1 !important;
  flex-direction: column;
  display: flex;
}

::v-deep .el-table__inner-wrapper {
  flex: 1 !important;
}

::deep(.el-table) {
  flex: 1 !important;
}

::v-deep .el-dialog__body {
  text-align: center !important;
}

::deep(.el-dialog__body) {
  text-align: center;
}

::deep(.el-table--enable-row-transition .el-table__body td.el-table__cell) {
  z-index: initial !important;
}

::v-deep .el-table--enable-row-transition .el-table__body td.el-table__cell {
  z-index: initial !important;
}
</style>
